package com.wyz.common.aop;


import com.wyz.Service.SysOperatorLogService;
import com.wyz.Service.SysOperatorLogService;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpSession;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;

/**
 * @ClassName LogAspect
 * @description: 自定义切面
 * @Version 1.0
 **/
@Aspect
@Component
public class LogAspect {

    /**
     * 操作日志service
     */
    @Autowired
    private SysOperatorLogService sysOperatorLogService;

    /**
     * 标注该方法体为后置通知，当目标方法执行成功后执行该方法体
     */
    @SuppressWarnings("static-access")
    @AfterReturning("execution(* com.wyz.controller.*.*(..))&&@annotation(sol)")
    public void addLogSuccess(JoinPoint jp, SystemLog sol) {
        Method method = getMethod(jp);
        if (method.isAnnotationPresent(SystemLog.class)) {
            HttpSession session = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest().getSession();
            String account = (String) session.getAttribute("orderName");
            //获取登录用户 TODO 这里根据系统逻辑来获取
            Annotation annotation = method.getAnnotation(SystemLog.class);
            if (annotation != null) {
                SystemLog log = (SystemLog) annotation;
                sysOperatorLogService.addLog(log.moduleName(), account, log.desc());
            }
        }
    }

    /**
     * 获取名称
     */
    private Method getMethod(JoinPoint pjp) {
        Method method = null;
        Class c = pjp.getTarget().getClass();
        Method[] ms = c.getMethods();
        for (Method m : ms) {
            if (m.getName().equals(pjp.getSignature().getName())) {
                method = m;
                break;
            }
        }
        return method;
    }
}
